package com.qf.shop.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DruidUtils {
    private static DruidDataSource dataSource;
    private static final ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal();

    static {
        Properties properties = new Properties();
        InputStream resourceAsStream = DruidUtils.class.getResourceAsStream("/db.properties");
        try {
            properties.load(resourceAsStream);
            dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        Connection connection = THREAD_LOCAL.get();
        try {
            if(connection == null){
                connection = dataSource.getConnection();
                THREAD_LOCAL.set(connection);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void begin(){
        Connection connection = getConnection();
        try {
            connection.setAutoCommit(false);//设置禁止自动启动
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void commit(){
        Connection connection = getConnection();
        try {
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close();
        }
    }

    public static void rollback(){
        Connection connection = getConnection();
        try {
            connection.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            close();
        }
    }


    public static void close(){
        Connection connection= getConnection();
        try {
            connection.close();
            THREAD_LOCAL.remove();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
